package com.reggie.console.controller;

import com.reggie.common.enums.ResponseCode;
import com.reggie.common.exception.ReggieException;
import com.reggie.console.annotation.AuthRule;
import com.reggie.console.dto.ResultDTO;
import com.reggie.console.enums.ReggieRole;
import com.reggie.console.util.ResultBuilder;
import com.reggie.service.facade.FileSystemFacade;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;

/**
 * 文件上传下载 前端控制器
 *
 * @author yth
 * @since 2023-02-05-22:55
 */
@Slf4j
@RestController
@RequestMapping("/common")
@AuthRule(roles = {ReggieRole.EMPLOYEE})
public class CommonController {

    @Autowired
    private FileSystemFacade fileSystemFacade;

    /**
     * 文件上传方法
     *
     * @param file 文件
     * @return 文件名称
     */
    @PostMapping("/upload")
    public ResultDTO<String> upload(MultipartFile file) {
        try {
            String originalFilename = file.getOriginalFilename();
            InputStream is = file.getInputStream();
            String filename = fileSystemFacade.saveImageFile(originalFilename, is);
            return ResultBuilder.ok(filename);
        } catch (IOException e) {
            throw new ReggieException(ResponseCode.SERVER_ERROR, "上传文件失败，获取文件输入流失败", e);
        }
    }

    /**
     * 文件下载
     *
     * @param name     文件名
     * @param response HttpServletResponse
     */
    @GetMapping("/download")
    public void downloadImg(String name, HttpServletResponse response) {
        response.setContentType("image/jpeg");
        try {
            fileSystemFacade.getLocalImageFile(name, response.getOutputStream());
        } catch (IOException e) {
            throw new ReggieException(ResponseCode.SERVER_ERROR, "下载文件失败，获取输出流失败", e);
        }
    }

}
